import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:juming_test/model/domain/domain_filter_item_model.dart';
import 'package:juming_test/model/domain/domain_filter_option_model.dart';

/// 选项按钮组件
class DomainFilterOption extends StatelessWidget {
  const DomainFilterOption({
    super.key,
    required this.model,
    required this.onChanged,
  });

  // 数据源
  final DomainFilterItemModel model;
  // 选中回调
  final Function(List<DomainFilterOptionModel>) onChanged;

  @override
  Widget build(BuildContext context) {
    final List<DomainFilterOptionModel> list = model.options;

    return Wrap(
      spacing: 12.w,
      runSpacing: 12.w,
      children:
          list.map((item) {
            final isSelected = item.isSelected;
            return GestureDetector(
              onTap: () {
                onItemTap(item, list);
              },
              child: Container(
                padding: EdgeInsets.symmetric(horizontal: 6.w, vertical: 6.w),
                decoration: BoxDecoration(
                  color: isSelected ? Colors.red[50] : Colors.grey[100],
                  border: Border.all(
                    color: isSelected ? Colors.redAccent : Colors.transparent,
                    width: 1.w,
                  ),
                  borderRadius: BorderRadius.circular(4.w),
                ),
                child: Text(
                  item.name,
                  style: TextStyle(
                    fontSize: 14.sp,
                    color: isSelected ? Colors.red[400] : Colors.black,
                  ),
                ),
              ),
            );
          }).toList(),
    );
  }

  // 点击事件
  void onItemTap(
    DomainFilterOptionModel item,
    List<DomainFilterOptionModel> list,
  ) {
    final isMultipleChoice = model.type == DomainFilterItemType.multipleChoice;
    List<DomainFilterOptionModel> newSelectedValues =
        list.where((element) => element.isSelected).toList();
    if (newSelectedValues.contains(item)) {
      newSelectedValues.remove(item);
      onChanged(newSelectedValues);
      return;
    }
    if (isMultipleChoice) {
      // 多选
      // 如果选中项为(不限)，取消别的选择
      if (item.value == "") {
        newSelectedValues.clear();
        newSelectedValues.add(item);
      } else {
        newSelectedValues.removeWhere((element) => element.value == "");
        newSelectedValues.add(item);
      }
    } else {
      // 单选
      newSelectedValues.clear();
      newSelectedValues.add(item);
    }
    onChanged(newSelectedValues);
  }
}
